<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="生产白夜班别" prop="shift">
        <el-select v-model="formData.shift" placeholder="请选择白夜班别">
          <el-option v-for="dict in getStrDictOptions(DICT_TYPE.MES_SHIFT)" :key="dict.value"
                     :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="开始时间点值" prop="startTimeValue">
        <el-time-picker
          class="w100"
          value-format="HH:mm:ss"
          format="HH:mm:ss"
          v-model="formData.startTimeValue"
          @change="startTimeValueChange"
          placeholder="开始时间点值"/>
      </el-form-item>
      <el-form-item label="开始时间点" prop="startTime">
        <el-input v-model="formData.startTime" placeholder="请输入开始时间点(用于页面展示)"/>
      </el-form-item>
      <el-form-item label="结束时间点值" prop="endTimeValue">
        <el-time-picker
          class="w100"
          value-format="HH:mm:ss"
          format="HH:mm:ss"
          v-model="formData.endTimeValue"
          @change="endTimeValueChange"
          placeholder="结束时间点值"/>
      </el-form-item>
      <el-form-item label="结束时间点" prop="endTime">
        <el-input v-model="formData.endTime" placeholder="请输入结束时间点(用于页面展示)"/>
      </el-form-item>
      <el-form-item label="显示标签" prop="label">
        <el-input v-model="formData.label" placeholder="请输入显示标签"/>
      </el-form-item>
      <el-form-item label="显示顺序" prop="orderNo">
        <el-input v-model="formData.orderNo" placeholder="请输入显示顺序"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {BaseTimePeriodApi, BaseTimePeriodVO} from "@/api/mes/basetimeperiod";
import {DICT_TYPE, getStrDictOptions} from "@/utils/dict";
import dayjs from "dayjs";

/** 时间段配置信息 表单 */
defineOptions({name: 'BaseTimePeriodForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  shift: undefined,
  label: undefined,
  time: undefined,
  startTime: undefined,
  startTimeValue: undefined,
  endTime: undefined,
  endTimeValue: undefined,
  orderNo: undefined,
})
const formRules = reactive({
  shift: [{required: true, message: '班别不能为空', trigger: 'blur'}],
  label: [{required: true, message: '显示标签不能为空', trigger: 'blur'}],
  time: [{required: true, message: '时间点不能为空', trigger: 'blur'}],
  startTime: [{required: true, message: '开始时间点不能为空', trigger: 'blur'}],
  startTimeValue: [{required: true, message: '开始时间点值不能为空', trigger: 'blur'}],
  endTime: [{required: true, message: '结束时间点不能为空', trigger: 'blur'}],
  endTimeValue: [{required: true, message: '结束时间点值不能为空', trigger: 'blur'}],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  console.log("Form:", id)
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BaseTimePeriodApi.getBaseTimePeriod(id)
      console.log("Form:", formData.value)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BaseTimePeriodVO

    if (formType.value === 'create') {
      await BaseTimePeriodApi.createBaseTimePeriod(data)
      message.success(t('common.createSuccess'))
    } else {
      await BaseTimePeriodApi.updateBaseTimePeriod(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    shift: undefined,
    label: undefined,
    time: undefined,
    startTime: undefined,
    startTimeValue: undefined,
    endTime: undefined,
    endTimeValue: undefined,
    orderNo: undefined,
  }
  formRef.value?.resetFields()
}

let startLabel = ref("")
let endLabel = ref("")
const startTimeValueChange = (value) => {
  let h = dayjs(dayjs().format("YYYY-MM-DD") + '' + value).format("H")
  console.log("Value:", h)
  formData.value.startTime = h
  startLabel.value = dayjs(dayjs().format("YYYY-MM-DD") + '' + value).format("HH:mm")
  formData.value.label = startLabel.value + "-" + endLabel.value
  formData.value.time = h
}
const endTimeValueChange = (value) => {
  let h = dayjs(dayjs().format("YYYY-MM-DD") + '' + value).format("H")
  console.log("Value:", h)
  formData.value.endTime = h
  if (value === "23:59:59") {
    endLabel.value = dayjs(dayjs().format("YYYY-MM-DD") + '' + "00:00:00").format("HH:mm")
    formData.value.endTime = 0
  }else{
    endLabel.value = dayjs(dayjs().format("YYYY-MM-DD") + '' + value ).format("HH:mm")
    formData.value.endTime = h
  }
  formData.value.label = startLabel.value + "-" + endLabel.value
}
</script>
